var app = getApp();
var plugin = requirePlugin("myPlugin")
Page({
  data: {
    sousuo: "",
    status: "",
    devices: [],
    connection: '',
    cont:'未连接',
    connectionstate: "未连接"
  },
  onLoad(){

  },
  onShow(){
    plugin.Init('wx2e57f901656b52e7')//初始化 需要传递你的appID
    var that = this;
    wx.getConnectedBluetoothDevices({
      success(res) {
        for (var i = 0; i<res.devices.length;i++){
          if (res.devices[i].name == 'DP-TL900'){
            that.setData({
              connectionstate: "已连接",
              printdeviceid: res.devices[i].deviceId
            })
          }
          if (res.devices[i].name == 'WXL-T12'){
            that.setData({
              cont: "已连接",
              weightdeviceid: res.devices[i].deviceId
            })
          }
        }
      }, fail: function () {
        that.setData({
          connectionstate: "未连接",
          cont: "未连接"
        })
      }
    })
    that.linkblue();
    that.refreshData();
  },
  scanCode() {
    plugin.scanCode();
  },
  linkblue(){
    var that = this;
    if (wx.openBluetoothAdapter) {
      wx.openBluetoothAdapter({
        success: function (res) {
          //得到蓝牙状态
          wx.getBluetoothAdapterState({
            success: function (res) {
              //that.data.isbleok = res.available;
              if (res.available) {
              }
              that.setData({
                //msg: "蓝牙状态" + ":" + JSON.stringify(res.errMsg),
                sousuo: res.discovering ? "在搜索。" : "未搜索。",
                status: res.available ? "蓝牙可用。" : "蓝牙不可用。",
              })
              //监听蓝牙适配器状态  
              wx.onBluetoothAdapterStateChange(function (res) {
                that.data.isbleok = res.available;
                that.setData({
                  sousuo: res.discovering ? "在搜索。" : "未搜索。",
                  status: res.available ? "蓝牙可用。" : "蓝牙不可用。",
                })
              })
            },
            fail: function () {
              wx.showModal({
                title: 'JDY软件',
                content: '请打开蓝牙',
                showCancel: false
              })
            }
          })
        },
        fail: function () {
          wx.showModal({
            title: 'JDY软件',
            content: '请打开蓝牙',
            showCancel: false
          })
        }
      })

    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示  
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false
      })
    }
  },
  scandev(){
    //首先要PUSH已经有的设备 
    var that = this;
    that.scan();
    wx.getBluetoothDevices({
      success: function (res) {
        var devices = res.devices;
        that.setData({
          msg: JSON.stringify(res.devices),
          devices: devices
        });
      }
    });
  },
  scan(){
    var that = this;
    //开始搜索咯
    // this.setData({devices: []});
    wx.showLoading({
      title: '正在搜索',
      mask: true,
    })
    setTimeout(function () {
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          wx.hideLoading();
          console.log(res)
          if (!that.data.devices[0]) {
            that.scandev();
          }
        },
        fail: function () {
          wx.hideLoading();
          wx.showModal({
            title: 'JDY软件',
            content: '停止搜索失败',
          })
        }
      })

    }, 1000 * 3)  //搜索10秒
    setTimeout(function () {
      wx.startBluetoothDevicesDiscovery({
        success: function (res) {
          that.onBluetoothDeviceFound(); //启动设备发现
        },
        fail: function (res) {
          wx.hideLoading();
          wx.showModal({
            title: '双兴智能',
            content: res.errMsg,
          })
        }
      })
    }, 100)
  },
  onBluetoothDeviceFound: function () {
    wx.onBluetoothDeviceFound(function (res) {

    })
  },
  //开始蓝牙连接 安桌可以直接这步
  StartConectDev: function () {
    var that = this;
    wx.showLoading({
      title: '连接中',
    })
    wx.createBLEConnection({
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        // 获取连接设备的service服务  
        setTimeout(function () {
          that.getBLService();
          wx.showModal({
            title: '双兴智能',
            content: '连接设备成功', // + that.data.connectedDeviceId,
            showCancel: false
          })
          if (that.data.shebeiname == 'WXL-T12') {
            that.setData({
              cont: "已连接"
            })
          }
        }, 100);
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showModal({
          title: '双兴智能',
          content: '连接设备失败,请重试', // + that.data.connectedDeviceId,
          showCancel: false
        })
      }
    })
  },
  // 获取连接设备的service服务  
  getBLService(){
    var that = this;
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        console.log('device services:', JSON.stringify(res));
        that.setData({
          services: res.services,
          // msg: JSON.stringify(res.services),
        }),
          setTimeout(function () {
            that.getBLcharac();//获取characterstic值
          }, 100)
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showModal({
          title: '双兴智能',
          content: res.errMsg,
        })
      }
    })
  },
  //获取连接设备的所有特征值  for循环获取不到值  
  //注意services是个数组
  getBLcharac(){
    var that = this;
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
      deviceId: that.data.connectedDeviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
      serviceId: that.data.services[0].uuid,
      //serviceId: that.data.serviceId,
      success: function (res) {
        for (var i = 0; i < res.characteristics.length; i++) {
          if (res.characteristics[i].properties.notify) {
            that.setData({
              // notifyServicweId: that.data.serviceId,
              notifyServicweId: that.data.services[0].uuid,
              notifyCharacteristicsId: res.characteristics[0].uuid,
            })
          }
          if (res.characteristics[i].properties.write) {
            if (res.characteristics.length >= 2) {
              var FFE2 = res.characteristics[1].uuid
            } else {
              var FFE2 = ""
            }
            that.setData({
              writeServicweId: that.data.services[0].uuid,
              //writeServicweId: that.data.serviceId,
              writeCharacteristicsId: res.characteristics[0].uuid,
              FFE2: FFE2
            })
          } else if (res.characteristics[i].properties.read) {
            that.setData({
              readServicweId: that.data.services[0].uuid,
              //readServicweId: that.data.serviceId,
              readCharacteristicsId: res.characteristics[0].uuid,
            })
          }
        }
        //开启监听
        //监听值变化
        setTimeout(function () {
          wx.notifyBLECharacteristicValueChange({
            state: true, // 启用 notify 功能  
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId: that.data.connectedDeviceId,
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
            serviceId: that.data.notifyServicweId,
            // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取  
            characteristicId: that.data.notifyCharacteristicsId,
            success: function (res) {
              // 这里的回调可以获取到 write 导致的特征值改变  
              wx.onBLECharacteristicValueChange(function (characteristic) {
                let buffer = characteristic.value
                let dataView = new DataView(buffer);
                var len2 = dataView.byteLength;
                that.setData({ receivcedatacount: that.data.receivcedatacount + len2 });
                let weight = parseFloat(ab2str(buffer).slice(8, -2))
                app.globalData.weight = weight; 
                if (that.data.HEXRev) {
                  that.setData({ receivcedata: that.data.receivcedata + ab2hex(buffer) });
                } else {
                  that.setData({ receivcedata: that.data.receivcedata + ab2str(buffer) });
                }
              })

            },
            fail: function (res) {
              wx.showModal({
                title: '双兴智能',
                content: res.errMsg,
                showCancel: false
              })
            }, complete: function () {
              wx.hideLoading(); //连接结束了
            }
          }) //nofify
        }, 100)  //监听


      },
      fail: function () {},
      complete: function () {}
    })
  },
  gotoSend(e){
    let that = this;
    let devices = that.data.devices;
    let id = e.currentTarget.dataset.id;
    let mac = devices[id].deviceId;
    // app.globalData.mac = mac;
    wx.getSystemInfo({
      success: function (res) {
        var mymac = "";
        mymac = mymac + ":" + mac;
        console.log(mymac)
        mymac = mymac.substr(1, 18).toUpperCase();
        // app.globalData.connectedDeviceId = mymac;
        that.setData({ 
          connectedDeviceId: mymac,
          shebeiname: devices[id].name,
          weightdeviceid: devices[id].deviceId
        });
        that.StartConectDev();
      }
    })
  },
  senddata(){
    var that = this;
    var data1 = that.data.sendddata;
    if (!data1) {
      wx.showToast({
        title: "请输入数据"
      })
      return;
    }
    that.setData({ senddatacount: that.data.senddatacount + data1.length });
    let buf;
    if (that.data.SendSet.length > 0) {
      //16进制换算及校验码
      if (data1.length % 2 == 0) {
        buf = that.hexStringToArrayBuffer(data1);
      } else {
        wx.showToast({
          title: "数据必须成两位一组",
          icon: "none"
        })
        return;
      }
    } else {
      buf = that.string2buffer(data1);
    }
    if (!ab2hex(buf)) {
      wx.showToast({
        title: "数据转换失败",
        icon: "none"
      })
      return;
    }
    var ffid = that.data.wcharffex == "FFE1" ? that.data.writeCharacteristicsId : that.data.FFE2;
    if (!ffid) {
      wx.showToast({
        title: "FFE2不存在"
      })
      return;
    }
    wx.writeBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.writeServicweId,
      characteristicId: ffid,
      value: buf,
      success: function (res) {
        //指令发送成功
        if (that.data.ReplSet.length == 0) {
          //停止了
          return;
        }
        setTimeout(function () {
          //发送数据
          that.senddata();
        }, 1000);

      },
      fail: function (res) {
        wx.showModal({
          title: 'JDY软件',
          content: res.errMsg,
          showCancel: false
        })
      },
    })
  },
  // 点击备注
  editname(){
    console.log(this.data.weightdeviceid);
  },
  // 打印机连接情况
  refreshData()//定时刷新
  {
    var that = this;
    setTimeout(function () {
      var mconnectionstate = plugin.getconnectionstate();//设备连接状态
      var mpaperstate = plugin.getpaperstate();
      if (mpaperstate) {
        that.setData({
          paperstate: "有纸"
        })
      } else {
        that.setData({
          paperstate: "无纸"
        })
      }
      if (mconnectionstate) {
        that.setData({
          connectionstate: "已连接"
        })
      } else {
        that.setData({
          connectionstate: "未连接"
        })
        that.refreshData();
      }
    }, 1000);
  }
})

// ArrayBuffer转为字符串，参数为ArrayBuffer对象
function ab2str(buf) {
  let dataView = new DataView(buf)
  var len2 = dataView.byteLength;
  var xx = "";
  for (let i = 0; i < dataView.byteLength; i++) {        
    //dataView.getUint8(i).toString(16);
    xx = xx + String.fromCharCode(dataView.getUint8(i))
  }
  return xx;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
